<?php

namespace App\Service\CallingCards;

use App\Enums\CallingCards\BaseEnum;
use App\Library\Rms\RmsCurl;
use App\Models\FeishuCallingCard\FeishuCallingCard;
use App\Models\FeishuCallingCard\FeishuCallingCardFranchisee;
use App\Models\FeishuCallingCard\FeishuCallingCardFranchiseeClue;
use App\Models\FeishuCallingCard\FeishuCallingCardInvitationLog;
use App\Models\FeishuCallingCard\FeishuCallingCardUser;
use App\Models\Kms\User\KmsUser;
use App\Service\Common\OssService;
use App\Service\OpenShop\Feishu\QualificationImageService;
use App\Service\OpenShop\User\RmsUserService;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Str;
use Kuafu\File\FileUtil;

class CardService
{
    const WX_LOGIN_SESSION_KEY = 'tiger:SESSION_KEY_UNIONID:';// 微信加盟小程序登陆返回的session_key

    public static function save(FeishuCallingCard $model, array $attr)
    {
        $original = $model->toArray();
        $model->fill($attr);
        $model->showPosition = (int)$attr['showPosition'];
        if (Str::startsWith($attr['avatar'], 'http')) {
            $tmp = parse_url($attr['avatar']);
            $model->avatar = ltrim($tmp['path'], '/');
        }

        // 判断是否需要更新图片
        $refresh = false;
        foreach (['name', 'mobile', 'position', 'showPosition', 'avatar'] as $key) {
            if ($model->{$key} != ($original[$key] ?? '')) {
                $refresh = true;
            }
        }
        if ($refresh) {
            $model->refreshWechatQrcode();
        }
        $model->save();

        // 每次修改完数据，重新生成分享图
        dispatch(function () use ($model) {
            CardService::updateWxShareImg($model);
        });

        return $model;
    }

    protected static function defaultCardInfo(): array
    {
        $feishuCallingCard = FeishuCallingCard::find(1);
        return static::cardInfo($feishuCallingCard);
    }

    public static function cardInfo(FeishuCallingCard $feishuCallingCard)
    {
        return [
            'id'                 => (string)$feishuCallingCard->id,
            'name'               => $feishuCallingCard->name,
            'mobile'             => $feishuCallingCard->mobile,
            'backgroundId'       => $feishuCallingCard->backgroundId,
            'originalCode'       => FileUtil::domain() . '/' . $feishuCallingCard->originalCode,
            'feishuId'           => $feishuCallingCard->feishuId,
            'showPosition'       => (bool)$feishuCallingCard->showPosition,
            'position'           => $feishuCallingCard->position,
            'wechatQrcode'       => strlen($feishuCallingCard->wechatQrcode) ? (FileUtil::domain() . '/' . $feishuCallingCard->wechatQrcode . '?x-oss-process=image/resize,w_750/quality,q_80') : '',
            'wechatId'           => $feishuCallingCard->wechatId ?: '',
            'avatar'             => strlen($feishuCallingCard->avatar) ? (FileUtil::domain() . '/' . $feishuCallingCard->avatar) : '',
            'companyAddressId'   => $feishuCallingCard->companyAddressId,
            'companyAddressName' => BaseEnum::OFFICES[$feishuCallingCard->companyAddressId]['name'] ?? '',
            'detailAddress'      => BaseEnum::OFFICES[$feishuCallingCard->companyAddressId]['address'] ?? '',
            'addressArr'         => array_values(BaseEnum::OFFICES),
            'posterPicture'      => FileUtil::domain() . '/' . $feishuCallingCard->wechatQrcode,
            'wxShareImg'         => $feishuCallingCard->wxShareImg ? FileUtil::domain() . '/' . $feishuCallingCard->wxShareImg : 'https://file.51kuafu.com/fb/99/1e8ca4d97a511b407a445ad0e527694b838d94ad8e90a7e8a19ed3f93e5d.jpeg',
            'type'               => 'employee',
        ];
    }

    //获取信息
    public static function getCardInfoById(FeishuCallingCardUser $user, string $id, int $shopId)
    {
        // 更新用户推荐人
        if ($id > 1 || 'u' === mb_substr($id, 0, 1)) {
            $user->invitorId = $id;
            if ($shopId) {
                $user->invitorId = "{$id}s{$shopId}";
            }
            $user->save();
        } else {
            $arr = explode('s', $user->invitorId);
            $id = $arr[0];
            $shopId = $arr[1] ?? 0;
        }
        $info = null;
        if ('u' === mb_substr($id, 0, 1)) {
            $franchisee = FeishuCallingCardFranchisee::query()
                ->where('uid', mb_substr($id, 1))
                ->first();
            $body = RmsUserService::getRmsUserInfoByUserIds([(int)mb_substr($id, 1)]);
            if (isset($body['data'][0]['id']) && $franchisee) {
                $shopInfo = RmsCurl::getIns()->do('api/internal/shop/getShopInfo', ['shopId' => $shopId], 'GET');
                $info = [
                    'id'                 => $user->invitorId,
                    'name'               => $body['data'][0]['username'],
                    'mobile'             => $body['data'][0]['mobile'],
                    'backgroundId'       => $franchisee->backgroundId,
                    'originalCode'       => FileUtil::domain() . '/' . $franchisee->wechatQrcode . '?x-oss-process=image/resize,w_750/quality,q_80',
                    'feishuId'           => '',
                    'showPosition'       => true,
                    'position'           => $franchisee->position,
                    'wechatQrcode'       => FileUtil::domain() . '/' . $franchisee->wechatUrl,
                    'wechatId'           => $body['data'][0]['wechatId'],
                    'avatar'             => $body['data'][0]['avatar'],
                    'companyAddressId'   => 0,
                    'companyAddressName' => '',
                    'detailAddress'      => $shopInfo['data']['address'] ?? '',
                    'addressArr'         => array_values(BaseEnum::OFFICES),
                    'posterPicture'      => FileUtil::domain() . '/' . $franchisee->wechatUrl,
                    'type'               => 'franchisee',
                ];
            }
        }
        if (is_numeric($id) && $id > 1) {
            if ($id) {
                $feishuCallingCard = FeishuCallingCard::find($id);
            } else {
                $feishuCallingCard = FeishuCallingCard::find($user->invitorId);
            }
            if ($feishuCallingCard) {
                if ($feishuCallingCard->wxShareImg == '') {//没有分享图 重新生成
                    dispatch(function () use ($feishuCallingCard) {
                        CardService::updateWxShareImg($feishuCallingCard);
                    });
                }
                $info = static::cardInfo($feishuCallingCard);
            }
        }
        if (null === $info) {
            $info = static::defaultCardInfo();
        }
        return $info;
    }

    //我的线索
    public static function getMyClue(int $invitationId, int $pageSize, int $pageNum)
    {
        $paginator = FeishuCallingCardFranchiseeClue::where('invitorId', $invitationId)
            ->orderBy('id', 'desc')
            ->paginate($pageSize, ['*'], 'page', $pageNum);
        return [
            'count'    => $paginator->total(),
            'list'     => array_map(function (FeishuCallingCardFranchiseeClue $v) {
                return [
                    'image'    => FileUtil::domain() . '/' . config('calling-cards.myClue'),
                    'name'     => $v->name,
                    'province' => $v->province,
                    'city'     => $v->city,
                    'district' => $v->district,
                    'time'     => $v->createdAt->toDateString(),
                ];
            }, $paginator->items()),
            'pageNum'  => $pageNum,
            'pageSize' => $pageSize,
        ];
    }


    public static function updateInvitor(FeishuCallingCardUser $user, int $invitorId)
    {
        if ($invitorId > 1) {
            $user->invitorId = $invitorId;
            $user->save();
            $invitationLogModel            = new FeishuCallingCardInvitationLog();
            $invitationLogModel->openid    = $user->openid;
            $invitationLogModel->invitorId = $invitorId;
            $invitationLogModel->save();
        }
    }

    /**
     * 更新微信分享名片图
     * @param FeishuCallingCard $card
     * @return string
     * @throws \OSS\Core\OssException
     */
    public static function updateWxShareImg(FeishuCallingCard $card): string
    {
        $cardInfo = CardService::cardInfo($card);
        $cardPath = QualificationImageService::wxCallingCardImage($cardInfo['avatar'], $cardInfo['name'], $cardInfo['showPosition'], $cardInfo['position'], $cardInfo['mobile'], $cardInfo['detailAddress'])['path'];

        $card->wxShareImg = $cardPath;
        $card->save();

        return $cardPath;
    }


    /**
     * 微信小程序用户更新信息
     * @param FeishuCallingCardUser $user
     * @param array $data
     * @return array
     */
    public static function updateWxUserInfo(FeishuCallingCardUser $user, array $data): array
    {
        if ($data && ($data['nickName'] || $data['headImage'])) {
            if ($data['nickName']) {
                $user->nickName = $data['nickName'];
            }
            if ($data['headImage']) {
                $user->headImage = $data['headImage'];
            }
            $user->save();
        }
        return [];
    }

    /**
     * 保存sessionKey
     * @param $unionId
     * @param $sessionKey
     */
    public static function setSessionKey($unionId, $sessionKey)
    {
        Redis::setex(self::WX_LOGIN_SESSION_KEY . $unionId, 259000, $sessionKey);
    }

    /**
     * 微信小程序用户授权更新用户手机号
     * @param FeishuCallingCardUser $user
     * @param string $encryptedData
     * @param string $iv
     * @return array
     * @throws \Exception
     */
    public static function updateUserMobile(FeishuCallingCardUser $user, string $encryptedData, string $iv): array
    {

        //获取用户sessionKey
        $sessionKey = Redis::get(self::WX_LOGIN_SESSION_KEY . $user->unionid);
        if (!$sessionKey) {
            throw new \Exception('获取sessionKey异常');
        }

        // 解密
        $decryptData = json_decode(self::decryptData($encryptedData, $iv, $sessionKey), true);

        //判断手机号是否已经绑定
        if (!$user->mobile || $user->mobile != $decryptData['purePhoneNumber']) {
            $user->mobile = $decryptData['purePhoneNumber'];
            $user->save();
        }
        return [];
    }


    /**
     * 解密
     * @param $encryptedData
     * @param $iv
     * @param $sessionKey
     * @return false|string
     * @throws \Exception
     */
    public static function decryptData($encryptedData, $iv, $sessionKey)
    {
        $appId = config('wechat.mini_program.callingCards.app_id');// 当前小程序appId
        Log::info(
            '解密原始数据:', [
                'data'  => $encryptedData,
                'iv'    => $iv,
                'key'   => $sessionKey,
                'appid' => $appId,
            ]
        );

        $aesKey    = base64_decode($sessionKey);
        $aesIV     = base64_decode($iv);
        $aesCipher = base64_decode($encryptedData);
        $result    = openssl_decrypt($aesCipher, 'AES-128-CBC', $aesKey, 1, $aesIV);
        $dataObj   = json_decode($result);
        if ($dataObj == null) {
            Log::error(
                '解密信息错误:', [
                'encryptedData' => $encryptedData,
                'iv'            => $iv,
                'sessionKey'    => $sessionKey,
                'msg'           => openssl_error_string(),
            ]
            );
            throw new \Exception('解密信息错误');
        }
        if ($dataObj->watermark->appid != $appId) {
            throw new \Exception('appId异常');
        }
        Log::info('解密数据结果:' . $result);
        return $result;
    }

    /**
     * 通过RMS用户ID添加夸父名片信息
     * @param $userId
     * @return void
     * @throws \OSS\Core\OssException
     */
    public static function addCallingCardByUserId($userId)
    {
        // 通过userId获得飞书用户信息
        $kmsUserModel = KmsUser::query()->where('rmsUserId', $userId)->first();

        if ($kmsUserModel == null) {
            return;
        }

        // 判断用户名片是否存在
        $callingCardModel = FeishuCallingCard::query()
            ->where('feishuId', $kmsUserModel->userId)
            ->first();

        if ($callingCardModel != null) {
            return;
        }

        // 获得飞书头像
        if (strlen($kmsUserModel->avatar)) {
            $tmp       = sys_get_temp_dir() . '/' . Str::random(10) . '.png';
            file_put_contents($tmp, file_get_contents($kmsUserModel->avatar));
            $arr = OssService::uploadFile($tmp);
            @unlink($tmp);
        }

        // 添加用户
        $m                   = new FeishuCallingCard();
        $m->feishuId         = $kmsUserModel->userId;
        $m->name             = $kmsUserModel->name . '(' . $kmsUserModel->nickname . ')';
        $m->realname         = $kmsUserModel->name;
        $m->mobile           = $kmsUserModel->mobile;
        $m->position         = $kmsUserModel->jobTitle;
        $m->companyAddressId = key(BaseEnum::OFFICES);
        $m->wechatQrcode     = '';
        $m->wechatId         = '';
        $m->avatar           = $arr['path'] ?? '15/7f/f36c8a1f2b66e4029eac2e181ea9fc781eb42529aed44397aad875dbbf5e.png';
        $m->departmentName   = $kmsUserModel->jobTitle;
        $m->save();
    }

}
